<?php
/**
 * Created by PhpStorm.
 * User: geolo
 * Date: 2018/9/5
 * Time: 18:23
 */
namespace app\modules\mch\models;
use app\models\LiveStream;
class LiveStreamForm extends Model
{
    public $wechat_app_id;
    public $pull_stream; // 小程序id
    public $push_stream;
    public function rules()
    {
        return [
            [['wechat_app_id', 'pull_stream','push_stream'], 'trim'],
            [['push_stream','pull_stream'],'string'],
            [['wechat_app_id','pull_stream','push_stream'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'wechat_app_id'=>'请先申请小程序',
            'push_stream' => '请填写推流地址',
            'pull_stream'=>'请填写拉流地址',

        ];
    }


    public function save()
    {
        if (!$this->validate())
            return $this->getModelError();

        $model = new LiveStream();
        $model->attributes = $this->attributes;

        $model->wechat_app_id = $this->wechat_app_id;

        $connection = \Yii::$app->db;
        $command = $connection->createCommand('SELECT count(*) as rcount FROM hjmall_stream where wechat_app_id='.$this->wechat_app_id);
        $num = $command->queryOne();
        if($num['rcount']<=0) {
            if ($model->save()) {
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                ];
            }
        }else{
            $upd = LiveStream::findOne(['wechat_app_id'=>$this->wechat_app_id]);
            $upd->push_stream = $this->push_stream;
            $upd->pull_stream = $this->pull_stream;
            if($upd->save()){
                return [
                    'code' => 0,
                    'msg' => '保存成功',
                ];
            }
        }
        return $this->getModelError($upd);
    }
}
